package de.playmee.services;

import android.content.Context;
import android.media.AudioManager;

/** 
 * Class to deal with audio focus. It can only be used on SDK level 8 and above,
 * since it uses API features that are not available on previous SDK's.
 */
public class AudioFocusHelper implements AudioManager.OnAudioFocusChangeListener {
    AudioManager audioManager;
    MusicFocusable musicFocusable;

    public AudioFocusHelper(Context context, MusicFocusable focusable) {
        audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
       musicFocusable = focusable;
    }
    
    /**
     * requests audio focus
     * 
     * @return true if request was successful, false otherwise
     */
    public boolean requestFocus() {
        return AudioManager.AUDIOFOCUS_REQUEST_GRANTED ==
        		audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
    }

    /**
     * abandons audio focus
     * 
     * @return true if request was successful, false otherwise
     */
    public boolean abandonFocus() {
        return AudioManager.AUDIOFOCUS_REQUEST_GRANTED == audioManager.abandonAudioFocus(this);
    }

    /** 
     * called by AudioManager on audio focus changes
     */
    public void onAudioFocusChange(int focusChange) {
        if (musicFocusable == null) {
        	return;
        }
        switch (focusChange) {
        	case AudioManager.AUDIOFOCUS_GAIN:
        		musicFocusable.onGainedAudioFocus();
                break;
        	case AudioManager.AUDIOFOCUS_LOSS:
        	case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
        		musicFocusable.onLostAudioFocus(false);
        		break;
        	case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
        		musicFocusable.onLostAudioFocus(true);
        		break;
        	default:
        }
    }
}
